package com.cn.por.util.html;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.IfStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.ModifierVisitor;
import com.github.javaparser.ast.visitor.Visitable;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.utils.CodeGenerationUtils;
import com.github.javaparser.utils.Log;
import com.github.javaparser.utils.SourceRoot;

import javax.servlet.http.HttpServletResponse;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通过java
 */
public class LogicPositivizer {
    /**
     * 需要修改的变量值
     * sourceBoot java类的根目录
     * javaName java类的名称
     */
    private static String sourceBoot
            ="D:\\develop\\idea\\fssp\\hsa-biz\\src\\main\\java\\cn\\hsa\\fssp\\modular\\bigscreen\\mztc\\provandcityReport\\controller\\ProvAndCityController.java";



    private static String startOne="import request from '@/utils/request'";
    private static String baseUrl="const BASE_URL = ";



    private static String postFunc =
            "export function {funcName}(params) { \n" +
            "   return request({\n"+
            "       url: BASE_URL + {funcUrl},\n"+
            "       method: 'post',\n"+
            "       data: params\n"+
            "   })\n"+
            "}\n";

    private static String getFunc =
            "export function {funcName}(params) { \n" +
                    "   return request({\n"+
                    "       url: BASE_URL + {funcUrl},\n"+
                    "       method: 'get'\n"+
                    "   })\n"+
                    "}\n";
    public static void main(String[] args) {
        // JavaParser has a minimal logging class that normally logs nothing.
        // Let's ask it to write to standard out:
        Log.setAdapter(new Log.StandardOutStandardErrorAdapter());
        StringBuffer sbImport = new StringBuffer();
        sbImport.append("import {");
        // SourceRoot is a tool that read and writes Java files from packages on a certain root directory.
        // In this case the root directory is found by taking the root from the current Maven module,
        // with src/main/resources appended.
        String rootDir =  sourceBoot.substring(0,sourceBoot.lastIndexOf("\\"));
        SourceRoot sourceRoot = new SourceRoot(CodeGenerationUtils.mavenModuleRoot(LogicPositivizer.class)
                .resolve(rootDir));

        String javaName =sourceBoot.substring(sourceBoot.lastIndexOf("\\")+1);
        // Our sample is in the root of this directory, so no package name.
        CompilationUnit cu = sourceRoot.parse("", javaName);
        StringBuffer sb= new StringBuffer();
        sb.append(startOne+"\n");

        // 遍历类
        for (ClassOrInterfaceDeclaration clazz : cu.findAll(ClassOrInterfaceDeclaration.class)) {
            // 输出类名
            System.out.println("类名：" + clazz.getNameAsString());

            // 获取类上的注解
            List<AnnotationExpr> classAnnotations = clazz.getAnnotations();
            for (AnnotationExpr annotation : classAnnotations) {
                String annotationStr = annotation.toString();
                if(annotationStr.startsWith("@RequestMapping")){
                    String regex = "\"([^\"]*)\"";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(annotationStr);

                    // 遍历匹配结果
                    while (matcher.find()) {
                        // 获取匹配到的内容
                        String match = matcher.group(0);
                        sb.append(baseUrl+match+"\n");
                    }
                }

            }

            // 遍历类的方法
            List<MethodDeclaration> mds =  clazz.getMethods();
            for (int j=0; j<mds.size(); j++) {
                MethodDeclaration method =mds.get(j);
                // 输出方法名
                StringBuffer urlParams=null;
                NodeList<Parameter> parameters = method.getParameters();
                for (int i = 0; i < parameters.size(); i++) {
                    Parameter item = parameters.get(i);
                    NodeList<AnnotationExpr> annotations = item.getAnnotations();
                    boolean need = true;
                    if(null!=annotations && annotations.size()>0){
                        if(annotations.get(0).getName().toString().equals("RequestBody")){
                            need =false;
                        }
                    }
                    if(item.getType().toString().equals("HttpServletResponse")){
                        need =false;
                    }
                    if(need){
                        if(null==urlParams){
                            urlParams = new StringBuffer();
                            urlParams.append("+ '?"+item.getName()+"='"+" + params."+item.getName());
                        }else{
                            urlParams.append("+"+"'&"+item.getName()+"=' " + " + params."+item.getName());
                        }

                    }
                }
                // 获取方法上的注解
                List<AnnotationExpr> methodAnnotations = method.getAnnotations();
                for (AnnotationExpr annotation : methodAnnotations) {
                    String funcAnaStr = annotation.toString();
                    if(funcAnaStr.startsWith("@RequestMapping")
                            || funcAnaStr.startsWith("@GetMapping")
                            || funcAnaStr.startsWith("@PostMapping")){
                        //获取方法上请求路径
                        String urlfunc ="";
                        if (annotation instanceof NormalAnnotationExpr) {
                            NormalAnnotationExpr normalAnnotation = (NormalAnnotationExpr) annotation;
                            // 获取注解的名称
                            String annotationName = normalAnnotation.getNameAsString();
                            // 获取注解的参数
                            List<com.github.javaparser.ast.expr.MemberValuePair> pairs = normalAnnotation.getPairs();
                            for (com.github.javaparser.ast.expr.MemberValuePair pair : pairs) {
                                String paramName = pair.getNameAsString();
                                String paramValue = pair.getValue().toString().replace("\"","");
                                if("value".equals(paramName)){
                                    urlfunc = "'"+paramValue+"'";
                                }
                            }
                        }else if(annotation instanceof SingleMemberAnnotationExpr){
                            SingleMemberAnnotationExpr expr = (SingleMemberAnnotationExpr) annotation;
                            urlfunc = String.valueOf(expr.getMemberValue());
                            // 获取注解的参数值（这里得到的是Object类型，需按实际情况进一步处理）

                        }


                        if(null!=urlParams){
                            urlfunc += urlParams;
                        }

                        String funcStr ="";
                        if(funcAnaStr.contains("RequestMethod.POST") || funcAnaStr.startsWith("@PostMapping")){
                            funcStr = postFunc;
                        }else{
                            funcStr = getFunc;
                        }
                        sb.append(
                                funcStr.replace("{funcName}",method.getNameAsString())
                                        .replace("{funcUrl}",urlfunc)
                        );

                    }

                }
                sbImport.append(method.getNameAsString());
                if(j<mds.size()-1){
                    sbImport.append(",");
                }
            }
            sbImport.append("} from \"@/api/\"");
        }
        System.out.println(sb.toString());
        System.out.println(sbImport.toString());

        //        cu.accept(new MethodVisitor(), null);
//

//        cu.accept(new ModifierVisitor<Void>() {
//            /**
//             * For every if-statement, see if it has a comparison using "!=".
//             * Change it to "==" and switch the "then" and "else" statements around.
//             */
//            @Override
//            public Visitable visit(IfStmt n, Void arg) {
//                // Figure out what to get and what to cast simply by looking at the AST in a debugger!
//                n.getCondition().ifBinaryExpr(binaryExpr -> {
//                    if (binaryExpr.getOperator() == BinaryExpr.Operator.NOT_EQUALS && n.getElseStmt().isPresent()) {
//                        /* It's a good idea to clone nodes that you move around.
//                            JavaParser (or you) might get confused about who their parent is!
//                        */
//                        Statement thenStmt = n.getThenStmt().clone();
//                        Statement elseStmt = n.getElseStmt().get().clone();
//                        n.setThenStmt(elseStmt);
//                        n.setElseStmt(thenStmt);
//                        binaryExpr.setOperator(BinaryExpr.Operator.EQUALS);
//                    }
//                });
//                return super.visit(n, arg);
//            }
//        }, null);
//
//        // This saves all the files we just read to an output directory.
//        sourceRoot.saveAll(
//                // The path of the Maven module/project which contains the LogicPositivizer class.
//                CodeGenerationUtils.mavenModuleRoot(LogicPositivizer.class)
//                        // appended with a path to "output"
//                        .resolve(Paths.get("output")));
    }



    // 自定义 Visitor 类，用于遍历方法
    private static class MethodVisitor extends VoidVisitorAdapter<Void> {
        @Override
        public void visit(MethodDeclaration md, Void arg) {
            super.visit(md, arg);

            // 输出方法名
            System.out.println("方法名：" + md.getNameAsString());

            // 在这里你可以进一步处理方法信息，例如获取参数、注解等
        }
    }
}